package com.WebMentorPro.system.controller;

import com.WebMentorPro.system.annotation.AuthCheck;
import com.WebMentorPro.system.common.BaseResponse;
import com.WebMentorPro.system.common.DeleteRequest;
import com.WebMentorPro.system.common.ErrorCode;
import com.WebMentorPro.system.common.ResultUtils;
import com.WebMentorPro.system.constant.UserConstant;
import com.WebMentorPro.system.exception.BusinessException;
import com.WebMentorPro.system.exception.ThrowUtils;
import com.WebMentorPro.system.model.dto.teacher.*;
import com.WebMentorPro.system.model.entity.Teacher;
import com.WebMentorPro.system.model.entity.User;
import com.WebMentorPro.system.model.vo.LoginTeacherVO;
import com.WebMentorPro.system.model.vo.TeacherVO;
import com.WebMentorPro.system.model.vo.UserVO;
import com.WebMentorPro.system.service.TeacherService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.WebMentorPro.system.constant.UserConstant.SALT;

/**
 * 异科导师接口
 *
 * @author bianxinyao
 */
@RestController
@RequestMapping("/teacher")
@Slf4j
@Api(tags = {"异科导师接口"})
public class TeacherController {

    @Resource
    private TeacherService teacherService;

    // region 登录相关

    /**
     * 异科导师注册
     *
     * @param teacherRegisterRequest
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("异科导师注册")
    public BaseResponse<Long> teacherRegister(@RequestBody TeacherRegisterRequest teacherRegisterRequest) {
        if (teacherRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        String teacherAccount = teacherRegisterRequest.getTeacherAccount();
        String teacherPassword = teacherRegisterRequest.getTeacherPassword();
        String checkPassword = teacherRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(teacherAccount, teacherPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        long result = teacherService.teacherRegister(teacherAccount, teacherPassword, checkPassword);
        return ResultUtils.success(result);
    }

    /**
     * 异科导师登录
     *
     * @param teacherLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("异科导师登录")
    public BaseResponse<LoginTeacherVO> teacherLogin(@RequestBody TeacherLoginRequest teacherLoginRequest, HttpServletRequest request) {
        if (teacherLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String teacherAccount = teacherLoginRequest.getTeacherAccount();
        String teacherPassword = teacherLoginRequest.getTeacherPassword();
        if (StringUtils.isAnyBlank(teacherAccount, teacherPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        LoginTeacherVO loginTeacherVO = teacherService.teacherLogin(teacherAccount, teacherPassword, request);
        loginTeacherVO.setUserRole("teacher");
        return ResultUtils.success(loginTeacherVO);
    }


    /**
     * 异科导师注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("异科导师注销")
    public BaseResponse<Boolean> teacherLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        boolean result = teacherService.teacherLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录老师用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    @ApiOperation("获取当前登录老师用户")
    public BaseResponse<LoginTeacherVO> getLoginTeacher(HttpServletRequest request) {
        Teacher teacher = teacherService.getLoginTeacher(request);
        return ResultUtils.success(teacherService.getLoginTeacherVO(teacher));
    }

    // endregion

    // region 增删改查

    /**
     * 创建异科导师
     *
     * @param teacherAddRequest
     * @return
     */
    @PostMapping("/add")
    @ApiOperation("创建异科导师")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addTeacher(@RequestBody TeacherAddRequest teacherAddRequest) {
        if (teacherAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(teacherAddRequest, teacher);
        teacher.setTeacherPassword(DigestUtils.md5DigestAsHex((SALT + teacher.getTeacherPassword()).getBytes()));
        teacher.setTeacherAvatar("http://39.98.107.158:9000/photo/1733738540041_cbcd416310ed426888ae4a1b66cf0dd6.png");
        teacher.setTeacherProfile("这是一个新老师");
        boolean result = teacherService.save(teacher);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建失败");
        return ResultUtils.success(teacher.getId());
    }

    /**
     * 删除异科导师
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("删除异科导师")
    public BaseResponse<Boolean> deleteTeacher(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = teacherService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(result);
    }

    /**
     * 更新异科导师
     *
     * @param teacherUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("更新异科导师")
    public BaseResponse<Boolean> updateUserByAdmin(@RequestBody TeacherUpdateRequest teacherUpdateRequest) {
        if (teacherUpdateRequest == null || teacherUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Teacher teacher = new Teacher();
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", teacherUpdateRequest.getId());
        Teacher oldTeacher = teacherService.getOne(queryWrapper);

        if (teacherUpdateRequest.getTeacherPassword() == null || teacherUpdateRequest.getTeacherPassword().equals("")) {
            teacherUpdateRequest.setTeacherPassword(oldTeacher.getTeacherPassword());
        }else {
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + teacherUpdateRequest.getTeacherPassword()).getBytes());
            teacherUpdateRequest.setTeacherPassword(encryptPassword);
        }
        if (teacherUpdateRequest.getTeacherAccount() == null || teacherUpdateRequest.getTeacherAccount().equals("")) {
            teacherUpdateRequest.setTeacherAccount(oldTeacher.getTeacherAccount());
        }
        if (teacherUpdateRequest.getTeacherAvatar() == null || teacherUpdateRequest.getTeacherAvatar().equals("")) {
            teacherUpdateRequest.setTeacherAvatar(oldTeacher.getTeacherAvatar());
        }
        if (teacherUpdateRequest.getTeacherName() == null || teacherUpdateRequest.getTeacherName().equals("")) {
            teacherUpdateRequest.setTeacherName(oldTeacher.getTeacherName());
        }
        if (teacherUpdateRequest.getTeacherProfile() == null || teacherUpdateRequest.getTeacherProfile().equals("")) {
            teacherUpdateRequest.setTeacherProfile(oldTeacher.getTeacherProfile());
        }

        BeanUtils.copyProperties(teacherUpdateRequest, teacher);
        boolean result = teacherService.updateById(teacher);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "更新失败");
        return ResultUtils.success(result);
    }

    /**
     * 分页获取异科导师列表（仅管理员）
     *
     * @param teacherQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("分页获取异科导师列表（仅管理员）")
    public BaseResponse<Page<TeacherVO>> listTeacherByPage(@RequestBody TeacherQueryRequest teacherQueryRequest) {
        long current = teacherQueryRequest.getCurrent() == 0 ? 1 : teacherQueryRequest.getCurrent();
        long size = teacherQueryRequest.getPageSize() == 0 ? 10 : teacherQueryRequest.getPageSize();

        Page<Teacher> pageParam = new Page<>(current, size);
        Page<TeacherVO> teacherVOPage = teacherService.getQueryByAll(pageParam, teacherQueryRequest);
        return ResultUtils.success(teacherVOPage);
    }

    /**
     * 分页获取异科导师的学生列表
     *
     * @param teacherQueryStuRequest
     * @return
     */
    @PostMapping("/get/my/student")
    @ApiOperation("分页获取异科导师的学生列表")
    public BaseResponse<Page<UserVO>> listTeacherByPage(@RequestBody TeacherQueryStuRequest teacherQueryStuRequest, HttpServletRequest request) {
        long current = teacherQueryStuRequest.getCurrent() == 0 ? 1 : teacherQueryStuRequest.getCurrent();
        long size = teacherQueryStuRequest.getPageSize() == 0 ? 10 : teacherQueryStuRequest.getPageSize();
        Long teacherId = teacherService.getLoginTeacher(request).getId();
        Page<User> pageParam = new Page<>(current, size);
        Page<UserVO> studentVOPage = teacherService.getQueryByMyStudent(pageParam, teacherQueryStuRequest,teacherId);
        return ResultUtils.success(studentVOPage);
    }

    // endregion
}
